<?php 

/**
 * 8-2-2012
 * GamerController
 * Klasa na potrzeby modulu testu pokazujacego autoryzacje ksiazka eazZend 186
 */ 
class GamerController extends Zend_Controller_Action 
{ 
	
	/**
	 * 
	 * Rejestracja uruchamiana po wpisaniu danych i przeladowaniu
	 * Waliduje jesi blad to zwraca dane, jezeli ni ma bledu filtruje (z hasla md5) i inset do bazy
	 */
	public function registerAction()
	{	
		// jezeli otrzymuje cos z posta
		if ($this->getRequest()->isPost()) 
		{
			#1.  w waliduje podane dane. tej walidacji troche juz tu jest wic dziala to jak normalna ju aplikacja
			
			// Valid email address?
			if (! Zend_Validate::is($this->_request->getPost('email'), 'EmailAddress')) 
			{
				$this->view->errors[] = "Invalid e-mail address.";
			} 
			
			// sprawdzenie czy taki email nie jst juz w bazie
			$user = new User();
			$foundUser = $user->getUserByEmail($this->_request->getPost('email'));
			if ($foundUser->id != "") 
			{
				$this->view->errors[] = "E-mail address already in database.";
			}
			
			// Handle must be between 2 and 20 characters
			$validHandle = new Zend_Validate_StringLength(2,20);
			if (! $validHandle->isValid($this->_request->getPost('handle'))) 
			{
				$this->view->errors[] = "Handle must be between 2 and 14 characters.";
			}
			
			// Handle must consist solely of alphanumeric characters
			$validHandle = new Zend_Validate_Alnum();
			if (! $validHandle->isValid($this->_request->getPost('handle'))) {
				$this->view->errors[] = "Handle must consist of letters and numbers.";
			} // end valid handle
			
			// Handle cannot already exist in database
			$foundUser = $user->getUserByHandle($this->_request->getPost('handle'));
			if ($foundUser->id != "") {
				$this->view->errors[] = "Handle already exists in database.";
			}
			
			// Password must be at least 6 characters
			$validPswd = new Zend_Validate_StringLength(6,20);
			if (! $validPswd->isValid($this->_request->getPost('password'))) 
			{
				$this->view->errors[] = "Password must be at least 6 characters.";
			} 
			
			// First name must not be empty
			$validFirstName = new Zend_Validate_NotEmpty();
			if (! $validFirstName->isValid($this->_request->getPost('first_name'))) 
			{
				$this->view->errors[] = "Please provide your first name.";
			} 
			
			// Last name must not be empty
			$validLastName = new Zend_Validate_NotEmpty();
			if (! $validLastName->isValid($this->_request->getPost('last_name'))) {
				$this->view->errors[] = "Please provide your last name.";
			} // end valid last name
			
			// Valid gender?
			if (! Zend_Validate::is($this->_request->getPost('gender'), 'NotEmpty')) 
			{
				$this->view->errors[] = "Please identify your gender.";
			}
			
			// jest blad wiec dane przesylam spowrotem do widokus
			if (count($this->view->errors) > 0) {
			
				$this->view->email = $this->_request->getPost('email');
				$this->view->handle = $this->_request->getPost('handle');
				$this->view->first_name = $this->_request->getPost('first_name');
				$this->view->last_name = $this->_request->getPost('last_name');
				$this->view->gender = $this->_request->getPost('gender');
			
			// No errors, add the user to the database and send the confirmation e-mail
			} 
			else 
			{
				// Generate the random key used for registration confirmation
				$registrationKey = $this->generate_random_string();
				
				// Prepare the data array for database insertion
				$data = array (
					'email' => $this->_request->getPost('email'),
					'password' => md5($this->_request->getPost('password')),
					'registration_key' => $registrationKey,
					'handle' => $this->_request->getPost('handle'),
					'first_name' => $this->_request->getPost('first_name'),
					'last_name' => $this->_request->getPost('last_name'),
					'gender' => $this->_request->getPost('gender'),
					'created_at' => date('Y-m-d H:i:s'),
					'updated_at' => date('Y-m-d H:i:s'),
					'last_login' => date('Y-m-d H:i:s')
				);
				
				// Insert the registration data into the database
				$user = new User();
				$user->insert($data);
			    
			}
	
		}
	}
	
	/**
	 * Proces logowania - uruchamiany jak dostane postem wiadomosc
	 * 
	 */
	public function loginAction()
	{
		if ($this->getRequest()->isPost()) 
		{
		
		// Retrieve the provided email address and password
		$email = $this->_request->getPost('email');
		$password = $this->_request->getPost('password');
		
		// Make sure the email and password were provided
		if (empty($email) || empty($password)) 
		{
		$this->view->errors[] = "Provide e-mail address and password.";
		} 
		else 
		{
		
		// Identify the authentication adapter CUKIER W CUKRZE !!!!!!!!!!!!!!!!!!!
		$authAdapter = new Zend_Auth_Adapter_DbTable($this->db);
		
		// Identify the table where the user data is stored
		$authAdapter->setTableName('users');
		
		// Identify the column used to store the "username"
		$authAdapter->setIdentityColumn('email');
		
		// Identify the column used to store the password
		$authAdapter->setCredentialColumn('password');
		
		// How is the password stored?
		$authAdapter->setCredentialTreatment('MD5(?)');
		
		// Pass the provided information to the adapter PRZEKAZANIE DO AUTORYZACJI EMAILA I PASWORDU
		// SEDNO SPRAWY !!  TUTAJ PODAWANY JEST EMAIL I HASLO
		$authAdapter->setIdentity($email);
		$authAdapter->setCredential($password);
		
		$auth = Zend_Auth::getInstance();
		$result = $auth->authenticate($authAdapter);
		
		/**
		 * jEST TO DOBRE  miesjsce na rozwazenie co daje wogole zend auth
		 * Bo na pierwszy rzut oka okazuje sie ze nic on nie daje co najwyzej interfejs
		 */
		
		// SPRAWDZENIE WYNIKU ZWRACANEGO PRZEZ ZENDAUTHA isValid() SPOKO
		if ($result->isValid()) 
		{
			// Retrieve the user so can update the login timestamp
			$user = new User();
			$updateLogin = $user->getUserByEmail($email);
		
			if ($updateLogin->confirmed == 1) 
			{
			
			// Update the login timestamp and save the row
			$updateLogin->last_login = date('Y-m-d H:i:s');
			$updateLogin->save();
			
			// Redirect the user to the index page
			$this->_redirect('/');
			
			} 
			else 
			{
				$this->view->errors[] = "The e-mail address associateh this account has not been confirmed.";
			}

		} 
		else 
		{
			$this->view->valid = 0;
			$this->view->errors[] = "Login failed.";
		}
		
		}
		
	}
}	
	
	/**
	* Completes password recovery process
	*/
	
	public function resetAction()
	{
	
		$this->view->pageTitle = "Reset your password";
		
		// If the form has been posted, reset the password
		if ($this->getRequest()->isPost()) {
		
		// Password must be at least 6 characters
		$valid_pswd = new Zend_Validate_StringLength(6,20);
		if (! $valid_pswd->isValid($this->_request->getPost('password'))) {
		$this->view->errors[] = "Password must be at least 6 characters.";
		} // end valid password
		
		if ($this->_request->getPost('password') !=
		$this->_request->getPost('password2')) {
		$this->view->errors[] = "Your passwords do not match.";
		}
		
		// No errors, so update the password
		if (count($this->view->errors) == 0) {
		
		$user = new User();
		$query = $user->select()->where('registration_key = ?',
		$this->_request->getPost('key'));
		$result = $user->fetchRow($query);
		
		if (count($result) == 1) {
		$result->password = md5($this->_request->getPost('password'));
		$result->save();
		$this->view->updated = 1;
		}
		
		} else {
		$this->view->success = 1;
		$this->view->key = $this->_request->getPost('key');
		}
		
		// User has clicked the emailed password recovery link. Find the user
		// using the recovery key, and prepare the password reset form
		} else {
		
		$recoveryKey = $this->_request->getParam('key');
		
		$user = new User();
		$query = $user->select()->where('registration_key = ?', $recoveryKey);
		
		$result = $user->fetchRow($query);
		
		if(count($result)) {
		$result->save();
		$this->view->success = 1;
		$this->view->key = $recoveryKey;
		} else {
		$this->view->errors[] = "Unable to locate password recovery key.";
		}
		
		}
	}	
	
	public function profileAction()
	{
		$handle = $this->_request->getParam('handle');
		$this->view->pageTitle = "Gamer Profile: {$handle}";
		$user = new User();
		$this->view->gamer = $user->getUserByHandle($handle);
		if ($this->view->gamer->id == "") {
			$this->view->errors[] = "This user does not exist.";
		}
	}	
	
	public function connectedAction()
	{
	
		// Set the page title
		$this->view->pageTitle = "Complete a GameNomad Connection";
		
		// Retrieve the invitation key
		$key = $this->_request->getParam('key');
		
		// Retrieve the invitation
		$invitation = new Invitation();
		$this->view->outstandingInvitation = $invitation->getInvitation($key);
		
		// Complete the invitation process
		$connected = $invitation->completeInvitation($key);
		
		// Determine the outcome response
		if ($connected) {
		$this->view->success = 1;
		} else {
		$this->view->errors[] = "We could not complete the connection request.";
		}
	
	}	
	
	/**
	* Generate a unique random string
	*
	* @param int $length Length of string to be generated
	* @return string $str Random string
	*/
	private function generate_random_string($length=32)
	{
		// Allowable random string characters
		$seeds = 'abcdefghijklmnopqrstuvwxyz0123456789';
		
		// Generate the random string
		$str = '';
		$count = strlen($seeds);
		for ($i = 0; $length > $i; $i++)
		{
		$str .= $seeds[mt_rand(0, $count - 1)];
		}
		
		return $str;
	}	
	
}	
?>